<?php

namespace backend\models;


use yii\base\Model;
use Yii;
use yii\rbac\Role;

/**
 * Class RoleForm
 *
 * @property bool $isNew
 * @package backend\models
 */
class RoleForm extends Model
{
    public $name;
    public $description;

    private $_role;

    public function __construct(Role $role = null, $config = [])
    {
        parent::__construct($config);
        if ($role !== null) {
            $this->_role = $role;
            $this->name = $role->name;
            $this->description = $role->description;
        }
    }

    public function rules()
    {
        return [
            [['name', 'description'], 'required'],
            ['name', 'match', 'pattern' => '/[a-z0-9]+/'],
            ['name', 'nameUnique'],
        ];
    }

    public function nameUnique()
    {
        if ($this->getIsNew() || $this->_role->name !== $this->name) {
            $role = Yii::$app->getAuthManager()->getRole($this->name);
            if ($role) {
                $this->addError('name', '名称已经被使用。');
            }
        }
    }

    public function attributeLabels()
    {
        return [
            'name' => '名称',
            'description' => '描述'
        ];
    }

    /**
     * @return bool
     */
    public function getIsNew()
    {
        return !isset($this->_role);
    }

    public function save()
    {
        if (!$this->validate()) {
            return false;
        }

        $authManager = Yii::$app->getAuthManager();
        if (!isset($this->_role)) {
            $role = $authManager->createRole($this->name);
            $role->description = $this->description;
            return $authManager->add($role);
        } else {
            $name = $this->_role->name;
            $this->_role->name = $this->name;
            $this->_role->description = $this->description;
            return $authManager->update($name, $this->_role);
        }
    }
} 